package com.cms.student;

import com.auxiliary.Util;
import com.doman.*;
import com.resultmsg.BaseEnums;
import com.resultmsg.Result;
import com.resultmsg.Results;
import com.server.BaseConfigMapper;
import com.server.ParentMapper;
import com.server.StudentMapper;
import com.server.TeacherParentMapper;
import java.time.Year;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.sonatype.inject.Parameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@RequestMapping(value = "/educloud")
@RestController
public class StudentController {

    @Autowired
    private StudentMapper mapper;

    @Autowired
    private BaseConfigMapper baseConfigMapper;
    @Autowired
    private ParentMapper parentMapper;
    @Autowired
    private TeacherParentMapper teacherParentMapper;

    /**
     * 条件搜索
     *
     * @param stuConditions
     * @return
     */
    @RequestMapping(value = "/students/conditions", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public Result getStudentsByCondition(@RequestBody StuConditions stuConditions) {
        try {
            List<Student> list = mapper.selectByCondition(stuConditions);
            if (list.size() > 0) {
                return Results.successWithData(list, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
            } else {
                return Results.failureWithData("", BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
            }
        } catch (Exception e) {
            return Results.failureWithData(e.getMessage(), BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        }
    }

    /**
     * 全局搜索
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/students", method = RequestMethod.GET)
    public Result getStudents() {
//        try {
        List<Student> list = mapper.selectAll();
        return Results.successWithData(list, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
//        } catch (Exception e) {
//            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
//        }
    }

    /**
     * 添加学生
     *
     * @param student
     * @return
     */
    @RequestMapping(value = "/students", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public Result addStudent(@RequestBody Student student) {

//        try {

        if (student.getBindcode().isEmpty()) {
            student.setBindcode(Util.getKcode("", 6));
        }

        int res = mapper.insertSelective(addYearGrade(student));
        if (res > 0)
            return Results.successWithData(student, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
        else
            return Results.failureWithData(res, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
//        } catch (Exception e) {
//            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
//        }
    }

    /**
     * 更新学生
     *
     * @param student
     * @return
     */
    @RequestMapping(value = "/students", method = RequestMethod.PUT, produces = {"application/json;charset=UTF-8"})
    public Result updateStudent(@RequestBody Student student) {

        try {
            int res = mapper.updateByBindCode(addYearGrade(student));
            if (res > 0)
                return Results.success(BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
            else
                return Results.failure(BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        } catch (Exception e) {
            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        }
    }

    /**
     * 删除学生
     *
     * @param student
     * @return
     */
    @RequestMapping(value = "/students", method = RequestMethod.DELETE)
    public Result delStudent(@RequestBody Student student) {
        try {
            List<Parent> list = parentMapper.selectByBindCode(student.getBindcode());
            for (Parent parent : list) {
                String[] split = parent.getBindcode().split(",");
                if (split.length <= 1){//删除
                    //删除家长信息
                    int i1 = parentMapper.deleteByPrimaryByOpenid(parent);
                    //删除关联关系表信息
                    TeacherParent teacherParent = new TeacherParent();
                    teacherParent.setOpenid(parent.getOpenid());
                    int i = teacherParentMapper.deleteByPrimaryByOpenid(teacherParent);
                    //删除学生
                    int res = mapper.delByBindCode(student.getBindcode());
                }else{//修改
                    //修改家长信息
                    String s1 = "";
                    for (String s : split) {
                        if (!s.equals(student.getBindcode())){
                            s1 += s+",";
                        }
                    }
                    for (int i = 0; i < split.length; i++) {
                        if (i == 0){
                            parent.setCurrentcode(split[i]);
                        }
                    }
                    parent.setBindcode(s1);
                    int i = parentMapper.updateByPrimaryByOpenid(parent);
                    //删除学生
                    int res = mapper.delByBindCode(student.getBindcode());
                }
            }
            //删除学生
            int res = mapper.delByBindCode(student.getBindcode());
            return Results.success(BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
        } catch (Exception e) {
            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        }
    }


    @RequestMapping(value = "/uploadStudent/{bindcode}", method = RequestMethod.POST)
    public Result upload(@RequestBody MultipartFile file, @PathVariable("bindcode") String bindcode) throws Exception {

//        List<BaseConfig > baseConfigs = getAllKcode();
        List<BaseConfig> baseConfigs = baseConfigMapper.selectByType("grade");

        InputStream in = null;

        System.out.println("file==" + file);
        try {
            //将file转InputStream
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将InputStream转XLSX对象（即表格对象）
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
        //获取表格的第一页
        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        //获取该页有多少数据
        int rowNum = xssfSheet.getLastRowNum();
        System.out.println("该页有多少数据：" + rowNum);
        int addcount = 0;
        if (rowNum < 1)
            return Results.failureWithData("无有效数据", BaseEnums.FAILURE.code(), BaseEnums.FAILURE.desc());

        List<Student> studentList = new ArrayList<>();

        try {
            for (int i = 1; i <= rowNum; i++) {


                Student student = new Student();

                //获取当前行
                XSSFRow xssfRow = xssfSheet.getRow(i);


                //id
                if (xssfRow.getCell(0) != null) {
                    xssfRow.getCell(0).setCellType(CellType.STRING);
//                    String icon = xssfRow.getCell(0).toString();
//                    student.setIcon(icon);
                }
                //icon
                if (xssfRow.getCell(1) != null) {
                    xssfRow.getCell(1).setCellType(CellType.STRING);
                    String icon = xssfRow.getCell(1).toString();
                    if (icon.length() > 255)
                        throw new Exception("第" + i + "行【头像】地址过长");
                    else
                        student.setIcon(icon);
                }
                //name
                if (xssfRow.getCell(2) != null) {
                    xssfRow.getCell(2).setCellType(CellType.STRING);
                    String name = xssfRow.getCell(2).toString();
                    if (name.equals(""))
                        throw new Exception("第" + i + "行【姓名】不能为空");
                    else{
                        if (name.length() <= 16) {
                            student.setName(name);
                        } else {
                            student.setName(name.substring(0, 16));
                        }

                    }

                } else {
                    //逻辑说明：姓名为空则认为数据结束
//                    throw new Exception("第" + i + "行【姓名】不能为空");
                    break;
                }
                //gradeno
                if (xssfRow.getCell(3) != null) {
                    xssfRow.getCell(3).setCellType(CellType.STRING);
                    String gradeno = xssfRow.getCell(3).toString();
                    if (gradeno.equals(""))
                        throw new Exception("第" + i + "行【年级】不能为空");
                    else {
                        String code = getKcode(baseConfigs, gradeno);
                        if (code == "kcode")
                            throw new Exception("第" + i + "行【年级】格式异常");
                        student.setGradeno(code);
                    }
                } else {
                    throw new Exception("第" + i + "行【年级】不能为空");
                }
                //classno
                if (xssfRow.getCell(4) != null) {
                    xssfRow.getCell(4).setCellType(CellType.STRING);
                    String classno = xssfRow.getCell(4).toString();
                    if (CheckExcelInput.isInteger(classno)) {
                        classno = classno.equals("") ? "999" : classno;
                        student.setClassno(classno);
                    } else {
                        throw new Exception("第" + i + "行【班级】格式异常" + classno);
                    }

                } else {
                    throw new Exception("第" + i + "行【班级】不能为空");
                }
                //stuno
                if (xssfRow.getCell(5) != null) {
                    xssfRow.getCell(5).setCellType(CellType.STRING);
                    int stuno = 0;
                    String icon = xssfRow.getCell(5).toString();
                    if (CheckExcelInput.isInteger(icon)) {
                        stuno = Integer.valueOf(icon);
                        if (stuno > 999)
                            throw new Exception("第" + i + "行【学号】过长");
                        else
                            student.setStuno(stuno);
                    } else {
                        throw new Exception("第" + i + "行【学号】格式异常");
                    }

                } else {
//                    throw new Exception("第" + i + "行【学号】不能为空");
                }

                //educode
                if (xssfRow.getCell(6) != null) {
                    xssfRow.getCell(6).setCellType(CellType.STRING);
                    String educode = xssfRow.getCell(6).toString();
                    if (educode.equals(""))
                        throw new Exception("第" + i + "行【学籍号】不能为空");
                    else if (educode.length() > 25)
                        throw new Exception("第" + i + "行【学籍号】过长");
                    else
                        student.setEducode(educode);
                } else {
                    throw new Exception("第" + i + "行【学籍号】不能为空");
                }
                //sex
                if (xssfRow.getCell(7) != null) {
                    xssfRow.getCell(7).setCellType(CellType.STRING);
                    int sex = xssfRow.getCell(7).toString().equals("男") ? 0 : 1;
                    student.setSex(sex);
                } else {
                    student.setSex(0);
                }
                //sfz
                if (xssfRow.getCell(8) != null) {
                    xssfRow.getCell(8).setCellType(CellType.STRING);
                    String sfz = xssfRow.getCell(8).toString();
                    student.setSfz(sfz);
                    if (sfz.length() <= 18) {
                        student.setTel(sfz);
                    } else {
                        student.setTel(sfz.substring(0, 18));
                    }
                }
                //tel
                if (xssfRow.getCell(9) != null) {
                    xssfRow.getCell(9).setCellType(CellType.STRING);
                    String tel = xssfRow.getCell(9).toString();
                    if (tel.length() < 11) {
                        student.setTel(tel);
                    } else {
                        student.setTel(tel.substring(0, 11));
                    }
                }
                //address
                if (xssfRow.getCell(10) != null) {
                    xssfRow.getCell(10).setCellType(CellType.STRING);
                    String address = xssfRow.getCell(10).toString();
                    if (address.length() > 50)
                        student.setAddress(address.substring(0, 50));
                }
                //organize
//                if (xssfRow.getCell(11) != null) {
//                    xssfRow.getCell(11).setCellType(CellType.STRING);
//                    String organize = xssfRow.getCell(11).toString();
//                    if (organize.equals(""))
//                        throw new Exception("第" + i + "行【组织结构】不能为空");
//                    else
//                        student.setOrganize(organize);
//                } else {
//                    throw new Exception("第" + i + "行【组织结构】不能为空");
//                }


                /**iptvbindcode   iptv激活码*/
                if (xssfRow.getCell(12) != null) {
                    xssfRow.getCell(12).setCellType(CellType.STRING);
                    String iptvbindcode = xssfRow.getCell(12).toString();
                    student.setIptvbindcode(iptvbindcode);
//                    if (sfz.length() <= 18) {
//                        student.setTel(sfz);
//                    } else {
//                        student.setTel(sfz.substring(0, 18));
//                    }
                }

                if(bindcode==null||bindcode.equals(""))
                    throw new Exception("第" + i + "行【组织结构】不能为空");

                student.setOrganize(bindcode);
                if (xssfRow.getCell(13) != null) {
                    xssfRow.getCell(13).setCellType(CellType.STRING);
                    String yearGrade = xssfRow.getCell(13).toString();
                    student.setYearGrade(yearGrade);
                }
                studentList.add(addYearGrade(student));

//                //防止重复插入
//                int res = 0;
//                do {
//                    res = insertStudent(student);
//                    if (res > 0) {
//                        addcount++;
//                    }
//                } while (res <= 0);


                //由于学号是纯数字，默认纯数字是以double传的，写进据库会变成科学计数法格式的，需要改为以string传进来
//            if (xssfRow.getCell(1).equals("") || xssfRow.getCell(1) == null)
//            System.out.println(i + "=jiaoyanicon：" + xssfRow.getCell(1).toString());
            }
        } catch (Exception e) {
//            System.out.println("catch::：" + e.toString());
//
            return Results.failureWithData("Excel::" + e.toString(), BaseEnums.FAILURE.code(), BaseEnums.FAILURE.desc());
        }

        try {
            for (int i = 0; i < studentList.size(); i++) {
                //防止重复插入
                int res = 0;
                do {
                    res = insertStudent(studentList.get(i));
                    if (res > 0) {
                        addcount++;
                    }
                } while (res <= 0);
            }
        } catch (Exception e) {
            return Results.failureWithData("SQL::" + e.toString(), BaseEnums.FAILURE.code(), BaseEnums.FAILURE.desc());
        }

        return Results.successWithData(addcount, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
    }

    private int insertStudent(Student student) {
        if (null == student.getBindcode() || "".equals(student.getBindcode())) {
            student.setBindcode(Util.getKcode("", 6));
        }
        int res = mapper.insertSelective(student);
        return res;
    }

    /**
     * 根据年级名称获取编码
     *
     * @param baseConfigs
     * @param gname
     * @return
     */
    private String getKcode(List<BaseConfig> baseConfigs, String gname) {

        String kcode = "kcode";
        for (int i = 0; i < baseConfigs.size(); i++) {
            BaseConfig bc = baseConfigs.get(i);
            System.out.println("批量导入：" + bc.getLabel() + "==" + gname);
            if (bc.getLabel().equals(gname)) {
                kcode = bc.getKcode();
                break;
            }
        }
        return kcode;
    }


    private static class CheckExcelInput {

        public static boolean checkSex(String sex) {
            return !sex.equals("男") && !sex.equals("女");
        }

//        public static boolean checkGradeno(String temp){
//            for (int i = 0; i < ; i++) {
//
//            }
//        }


        public static boolean isInteger(String str) {
            Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
            return pattern.matcher(str).matches();
        }

    }

	/**
	 * 填充学生字段
	 *
	 * @param student
	 * @return
	 */
	private Student addYearGrade(Student student){
		if (StringUtils.isNotBlank(student.getYearGrade())) {
			return student;
		}
		if (StringUtils.isNotBlank(student.getGradeno())) {
			Integer year = Integer.parseInt(Year.now().toString());
			String gradeNo = student.getGradeno();
			Integer diff = Integer.parseInt(gradeNo.substring(gradeNo.length() -1));
			Integer yearInt = year;
			//初中
			if (diff >= 7) {
				yearInt = year-(diff-7);
			}else{
				yearInt = year-(diff-1);
			}
			student.setYearGrade(yearInt +"级");
		}
		return student;

	}

}
